package FenxiaoService

import (
	"context"
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/library/response"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"strings"
	"time"
)

func AddGoods(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	goodsIds := strings.Split(r.GetString("goods_ids"), ",")
	oneRate := r.GetFloat64("one_rate", 0)
	twoRate := r.GetFloat64("two_rate", 0)
	threeRate := r.GetFloat64("three_rate", 0)
	if len(goodsIds) < 1 {
		return response.SuccessByRequestMessage(r, "成功")
	}
	err := g.DB().Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
		for _, item := range goodsIds {
			val, err := tx.Model("fenxiao_goods").Unscoped().Where("goods_id", item).
				Fields("id").Value()
			if err != nil {
				return err
			}
			if val.IsEmpty() {
				fgId, err := tx.Model("fenxiao_goods").Unscoped().InsertAndGetId(g.Map{
					"goods_id":  item,
					"create_at": time.Now().Unix(),
				})
				if err != nil {
					return err
				}
				_, err = tx.Model("fenxiao_goods_level").InsertAndGetId(g.Map{
					"fenxiao_goods_id": fgId,
					"goods_id":         item,
					"level_id":         1, // 先增加默认等级的
					"one_rate":         oneRate * 1000,
					"two_rate":         twoRate * 1000,
					"three_rate":       threeRate * 1000,
					"create_at":        time.Now().Unix(),
				})
				if err != nil {
					return err
				}
			} else {
				fgId := val.Int()
				_, err := tx.Model("fenxiao_goods").Unscoped().Where("id", fgId).Update(g.Map{
					"update_at": time.Now().Unix(),
					"status":    1,
					"delete_at": 0,
				})
				if err != nil {
					return err
				}
				_, err = tx.Model("fenxiao_goods_level").Where(g.Map{
					"fenxiao_goods_id": fgId,
					"goods_id":         item,
					"level_id":         1, // 只 默认等级的
				}).Update(g.Map{
					"one_rate":   oneRate * 1000,
					"two_rate":   twoRate * 1000,
					"three_rate": threeRate * 1000,
					"update_at":  time.Now().Unix(),
				})
				if err != nil {
					return err
				}
			}
		}
		return nil
	})
	if err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}

	return response.SuccessByRequestMessage(r, "成功")
}
